<?php

namespace app\models;

use cccmvc\exception\DatabaseException;

class User extends \cccmvc\Model
{
    public int $id = 0;
    public string $username;
    public string $email;
    public string $password;

    public function __construct(?int $userid = null)
    {
        parent::__construct();

        $this->setTable('users');
        if ($userid) {
            $this->setUserToAttr($this->find($userid));
        }
    }

    public function id()
    {
        return $this->id;
    }

    public function create($data)
    {
        $username = $data['username'] ?? '';
        $password = password_hash($data['password'] ?? '', PASSWORD_BCRYPT);
        $email = $data['email'] ?? '';

        $sql = "INSERT INTO " . $this->getTable() . " (username, email, password, is_deleted) VALUES (:username, :email, :password, :is_deleted)";

        $sql = $this->db->prepare($sql);
        $res = $sql->execute([":username" => $username, ':password' => $password, ':email' => $email, ':is_deleted' => null]);

        if ($res === false) {
            throw new DatabaseException($sql->errorInfo()[2] ?? 'Database error!', $sql->errorInfo()[1] ?? 0);
        }

        $handle = $this->db->prepare('SELECT LAST_INSERT_ID()');
        $handle->execute();
        $id = $handle->fetchColumn();

        $this->setUserToAttr([
            'id' => $id,
            'email' => $email,
            'username' => $username,
            'passowrd' => $password,
            'is_deleted' => null
        ]);

        return $this;
    }

    public function getTable(): string
    {
        return $this->table;
    }

    public function getUserData(array $where)
    {
        $paramArr = [];
        $valueArr = [];

        foreach ($where as $k => $v) {
            $paramArr[] = sprintf("%s=:%s", $k, $k);
            $valueArr[sprintf(":%s", $k)] = $v;
        }
        $sql = "SELECT * FROM " . $this->getTable() . " WHERE " . implode(',', $paramArr);
        $query = $this->db->prepare($sql);
        $query->execute($valueArr);

        if ($data = $query->fetch()) {
            $this->setUserToAttr($data);
        }

        return $this;
    }

    private function setUserToAttr($user): void
    {
        foreach ($user as $k => $v) {
            if (property_exists($this, $k)) {
                $this->$k = $v;
                $this->attributes[$k] = $v;
            }
        }
    }
}